<!DOCTYPE html>
<html lang="en" xmlns="">

<head>
    <meta charset="UTF-8">
    <!--适配手机端-->
    <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>

    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;

        }
        html,body{
            width: 100%;
            height: 100%;
            background-color: rgba(20, 40, 40, 0.98);
            overflow: auto;
        }
        .outer{
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            color: rgba(255, 255, 255, 0.48);
        }
        .outer .bookList{
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 20px;


        }
        .outer .bookList div{
            border: rgba(17, 21, 21, 0.39) 1px solid;
            border-radius: 4px;
            margin-top: 2px;
            width: 95%;
            height: 80px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .outer .inputContainer{
            width: 100%;
            height: 70px;
            display:flex;
            flex-direction: column;
            justify-content: space-evenly;
            align-items: center;
        }
        .outer .inputContainer button{
            background-color: rgba(0, 0, 0, 0.84);
            color: rgba(255, 255, 255, 0.75);
           margin-top: 5px;
            border-radius: 4px;
        }
        .outer .inputContainer .upload
        {

            width: 70%;
            height: 50px;
            background-color: rgba(81, 82, 159, 0.6);
            border: rgba(20, 40, 40, 0.98) 2px solid;
            border-radius: 3px;
            color: #ff0000;
            display: flex;
            text-align: center;
            margin-top: 5px;
        }

    </style>
</head>
<body oncopy="return false"
      oncut="return false;"
      onselectstart="return false"
      oncontextmenu="return false">
<div class="outer">
    <div class="inputContainer">
        <div class="input_refresh" style="margin-top:3px;height: 60px;display: flex;justify-content:space-evenly;align-items: center">
            <input class="upload" type="file" />
            <button onclick="refresh()">刷新</button>
        </div>
        <button onclick="uploadFile()">开始转换pdf为电子书</button>
      <!--  <div class="looktv" onclick="looktv()" style=";margin-top: 3px;font-size: 10px;color: red">看电视</div>-->
    </div>

    <div class="bookList"></div>
</div>

</body>
<script src="./static/js/jquery.min.js"></script>
<script src="./static/layer-v3.5.1/layer/layer.js"></script>
<script>
    let baseUrl="http://"+window.location.host+"/"

    initPage()
    function initPage() {
        try {
            StopMyTTS.callback()
        }catch (e) {
            
        }
        $.ajax({
            url:baseUrl+"getBookList",
            type:'post',
            async:true,
            beforeSend: function(jqXHR, settings) {
             /*   layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                })*/
            },
            success:function (data) {
                let bookName=data.toString().split("\n")
                let html=``
                for(let i=0;i<bookName.length;i++)
                {
                    if(bookName[i]!=="\n"&&bookName[i]!=="") {
                        //传入字符串一定要加''！！！
                        //字符中不要包含：'、"等字符，会产生错误

                        html = html + `<div style="margin-bottom: 10px" onclick="lookBook('${bookName[i]}')" "><p>${bookName[i]}</p></div>`
                    }
                }
                let insert=document.querySelector(".bookList")
                insert.innerHTML=html;
             //   layer.closeAll("loading")
            },
            error:function (data) {
                alert("获取书籍列表失败")
            }
        })
    }

    function lookBook(bookName) {
        try
        {
            $.ajax({
                url:baseUrl+"initBook",
                async:true,
                type:'post',
                data:{bookName:bookName},
                success:function (data) {
                    window.location.href=baseUrl+"lookbook"

                },
                error:function (data) {
                    alert("查看图书失败")
                }
            })
        }catch (e) {
            alert(e)
         console.log(e)
        }
    }


</script>
<!--切割文件并上传-->
<script>
    let second=0//记秒
    function uploadFileWithAsync(){
        let t=null
            //定时更新进度
            t=setInterval(function () {
                $.ajax({
                    url: baseUrl+"getProgress",
                    dataType:'json',
                    type:'get',
                    async: true,
                    success:function (data) {
                        let json=JSON.parse(JSON.stringify(data))
                        //  alert(data)
                    },
                    error:function (data) {
                        second=second+1
                        let json=JSON.parse(JSON.stringify(data))
                        //alert(json.responseText.split("\n")[2])
                        let p=document.querySelector("#progress")
                        let p1=json.responseText.split("\n")[0]
                        let p2=json.responseText.split("\n")[1]
                        let p3=json.responseText.split("\n")[2]
                        if(p1!==undefined&&p2!==undefined&&p3!==undefined) {
                            let html = `<p>${p1}/${p2}</p><p>${p3}</p><p>${second}秒</p>`
                            p.innerHTML = html
                        }
                    }
                })
            },1000)
       let defer=$.Deferred()
        const chunkSize = 2 * 1024*1024;// 每个chunk的大小，2兆
        let upload=document.querySelector(".upload")
        let file=upload.files[0]
        const totalChunk = Math.ceil(file.size / chunkSize); // 分片总数
        for(let i=0;i<totalChunk;i++)
        {
            let startLength = i * chunkSize; //当前上传文件块的起始位置
            let endLength = Math.min(file.size, startLength + chunkSize);
            let blobSlice = File.prototype.slice
            let formData = new FormData();
            formData.append("file", blobSlice.call(file, startLength, endLength));
            formData.append("startLength",startLength.toString());
            formData.append("fileName",file.name);
            formData.append("currentChunk",(i+1).toString())
            formData.append("totalChunk",totalChunk.toString())
           $.ajax({
                url: baseUrl+"upload",
                dataType:'json',
                type:'POST',
                async: true,//异步上传无法保证上传顺序
               //参考连接：https://blog.csdn.net/good_good_xiu/article/details/123002543
               data: formData,
                processData : false, // 使数据不做处理
                contentType : false, // 不要设置Content-Type请求头
                success: function(data){
                    let json=JSON.parse(JSON.stringify(data))
                    if(json.responseText==="allSuccess")
                    {
                        alert("转换完毕")
                        console.log("转换完毕")
                        defer.resolve(data)//手动设置deferred为完成态，执行done()回调
                    }

                },
                error:function(data){
                    let json=JSON.parse(JSON.stringify(data))
                  if(json.responseText==="上传文件成功"||json.responseText==="allSuccess")
                    {

                        if(json.responseText==="allSuccess")
                        {
                            defer.resolve(t)//手动设置deferred为完成态，执行done()回调
                        }
                    }
                    console.log("ajax失败回调：\n"+data)
                   // defer.reject(data)//手动设置deferred为失败，执行fail()回调
                }
            });
        }
       return defer
    }
    function uploadFile() {
        let upload = document.querySelector(".upload")
        let file = upload.files[0]
        if (file.size !== 0) {
           /* layer.load(1, {
                shade: [0.1, '#fff'] //0.1透明度的白色背景
            })*/
            showProgressPopup("<p>正在加载......</p>","进度")

            $.when(uploadFileWithAsync()).done(function (t) {
                layer.closeAll("loading")
                clearInterval(t)
                let p=document.querySelector("#progress")
                let html=`<p>转换完毕</p>`
                p.innerHTML=html
                setTimeout(function () {
                    // let m=document.getElementById("layui-layer-close")
                    //m.click()
                    //let cP=document.querySelector(".layui-layer-setwin")
                    //cP.style.textDecoration="none"
                    let close = document.querySelector(".layui-layer-close")
                    close.style.textDecoration = "none"
                    close.style.visibility = "visible"
                    close.style.color = "red"
                    close.style.fontSize = "15px"
                    close.innerHTML = "确定"
                    close.style.width = "100%"
                },10)
                second=0

               // alert("文件转换成功")
                initPage()

            }).fail(function (data) {
                console.log(data)
                layer.closeAll("loading")
            })
        }
        else
            alert("文件为空！")

    }
</script>
<!--展示文件转换进度-->
<script>
    //将传入的文本o以弹窗的形式展示出来
    function showProgressPopup(o,title) {
        layer.open({
            type: 1,
            skin: 'layui-layer-demo', //样式类名
            closeBtn: 1, //显示关闭按钮(0不显示)
            anim: 2,
            shadeClose: false, //开启遮罩关闭(就是点击空白部分自动关闭)

            content: '<div id="progress" style="display: flex;flex-direction: column;justify-content: center;align-items: center;font-size: 17px;;color: red;;overflow-y: auto;">' + o + '</div>',//可以是html
            title:`<p style="padding:0;color: red ;">${title}</p>`,//没有title
            resize: false,//不允许拉伸
            move: ".layui-layer-title"//触发拖动元素，默认时title，改成content,手机端浏览器无法拖动
            ,offset:['200px','30px']//弹出框在屏幕的位置,你可以offset: '100px'。当您top、left都要定义时，你可以offset: ['100px', '200px']。除此之外，你还可以定义offset: 'rb'，表示右下角。
        });
        /*设置弹出框内容的背景色*/
        document.querySelector(".layui-layer-demo").style.backgroundColor = "rgba(1,1,1,0.5)"
        document.querySelector(".layui-layer-demo").style.width = "300px"
        document.querySelector(".layui-layer-demo").style.height = "200px"
        document.querySelector(".layui-layer-demo").style.display= "flex"
        document.querySelector(".layui-layer-demo").style.flexDirection='column'
        /*设置标题的颜色和样式*/
        document.querySelector(".layui-layer-title").style.backgroundColor = "rgba(130,17,31,0.4)"
        document.querySelector(".layui-layer-title").style.height='50px'
        document.querySelector(".layui-layer-title").style.height='50px'
        document.querySelector(".layui-layer-title").style.padding='0'//清除自带的padding
        document.querySelector(".layui-layer-title").style.display= "flex"
        document.querySelector(".layui-layer-title").style.justifyContent= "center"
        document.querySelector(".layui-layer-title").style.alignItems= "center"


        document.querySelector(".layui-layer-close").style.visibility= "hidden"
        document.querySelector(".layui-layer-close").setAttribute("id","layui-layer-close")

        /*layui在手机端无法拖拽*/
        if(navigator.userAgent.match("Android")||navigator.userAgent.match("IOS"))
        {
            dragAndDropForPhone(document.querySelector(".layui-layer-title"),document.querySelector(".layui-layer-demo"))
        }
    }

    function dragAndDropForPhone(e,parent) {
        var startX = 0; // 获取手指初始坐标
        var startY = 0;
        var x = 0; // 获得盒子原来的位置
        var y = 0;
        // 手指触摸
        e.addEventListener('touchstart', function(e) {
            //  获取手指初始坐标
            startX = e.targetTouches[0].pageX;
            startY = e.targetTouches[0].pageY;
            //x = this.offsetLeft;
            //y = this.offsetTop;
            x=parent.offsetLeft
            y=parent.offsetTop;
            //this.style.boxShadow = '0 0 15px rgba(0, 0, 0, .6)';
            parent.style.boxShadow = '0 0 15px rgba(0, 0, 0, .6)';
        });
        // 手指离开
        e.addEventListener('touchend', function(e) {
            //this.style.boxShadow = '';
            parent.style.boxShadow = '';
        });

        // 手指按住移动
        e.addEventListener('touchmove', function(e) {
            //  计算手指的移动距离：手指移动之后的坐标减去手指初始的坐标
            var moveX = e.targetTouches[0].pageX - startX;
            var moveY = e.targetTouches[0].pageY - startY;
            // 移动盒子 盒子原来的位置 + 手指移动的距离

            //this.style.left = x + moveX + 'px';
            //this.style.top = y + moveY + 'px';
            parent.style.left = x + moveX + 'px';
            parent.style.top = y + moveY + 'px';
            e.preventDefault(); // 阻止屏幕滚动的默认行为
        });

    }
</script>
<!--查询是否可安全退出app，没有用了-->
<script>
    canExit()
   function canExit () {
        /*
       $.ajax({
            url: baseUrl + "canExit",
            type: 'post',
            async: true,
            success: function (data) {
                let waring = document.querySelector(".waring")
                waring.style.display = "none"
            },
            error: function (data) {
                alert("获取书籍列表失败")
            }
        })*/
    }

    function refresh() {
        window.location.href=baseUrl+"main"
    }

</script>
</html>